package com.kingmed.kmss.bpmn.flow.listener;

import com.kingmed.kmss.bpmn.modules.backup.service.BizApprovalStatusService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;

import com.kingmed.kmss.bpmn.flow.service.msg.BpmnMsgServiceImpl;
import com.kingmed.kmss.bpmn.flow.service.custom.ProcessStatusSyncServiceImpl;
import com.kingmed.kmss.common.constant.bpmn.BpmnConstant;
import com.kingmed.kmss.common.constant.bpmn.ProcessConstant;
import com.kingmed.kmss.common.enums.bpmn.ProcessType;
import com.kingmed.kmss.common.utils.AppContextUtil;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 流程结束 CompleteExecution listener
 * 
 * 回调业务接口更新流程状态
 * @author wzg
 *
 *
 */
@Slf4j
public class ProcessCompleteExecutionListener implements ExecutionListener {
	
	BizApprovalStatusService bizStatusSvc = AppContextUtil.getBean(BizApprovalStatusService.class);
	BpmnMsgServiceImpl msgSvc = AppContextUtil.getBean(BpmnMsgServiceImpl.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = -3036908590927665209L;

	ProcessStatusSyncServiceImpl procStatusSvc = AppContextUtil.getBean(ProcessStatusSyncServiceImpl.class);

	@Override
	public void notify(DelegateExecution execution) {

		String bizType = (String) execution.getVariable(BpmnConstant.VarKeys.BIZ_TYPE);
		String bizTitle = (String) execution.getVariable(BpmnConstant.VarKeys.BIZ_TITLE);
		String bizId = (String) execution.getVariable(BpmnConstant.VarKeys.BIZ_ID);
		boolean approved = (boolean) execution.getVariable(BpmnConstant.VarKeys.APPROVED);
		ProcessType processType = (ProcessType) execution.getVariable(BpmnConstant.VarKeys.PROCESS_TYPE);
		String procInstId = execution.getProcessInstanceId();
		String contractEndDate = (String) execution.getVariable(BpmnConstant.VarKeys.CONTRACT_END_DATE);
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put(BpmnConstant.VarKeys.CONTRACT_END_DATE, contractEndDate);
		
		bizStatusSvc.saveProcessCompleteStatus(bizType, bizId, approved, procInstId);
		log.debug("流程结束ExecutionListener, businessType:businessId: {}/{}",
				bizType, bizId
				);
		if(approved) {
			procStatusSvc.syncProcessStatus(bizType, bizId, bizTitle, ProcessConstant.Status.APPROVED, processType, paramMap);
			msgSvc.send(bizType, bizId, null, null, procInstId);
		}else{
			procStatusSvc.syncProcessStatus(bizType, bizId, bizTitle, ProcessConstant.Status.REJECTED, processType, paramMap);
		}
		
	};
	
}
